package com.fxust.dao;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.sql.Blob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.fxust.common.ConnectionPoolManager;
import com.fxust.utils.FileUtils;
import com.fxust.utils.UUIDUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * sql执行类
 *
 * @author johnking
 * @create 2017-12-19 下午11:08
 **/
public class ThirdTableDao {

    private static Logger logger = LoggerFactory.getLogger(ThirdTableDao.class);

    /**
     *
     * @author fgq 2017年8月8日 下午2:08:47
     * @param sql
     * @param fields
     * @return
     */
    public synchronized List<Map<String, Object>> queryBlobPicData(String sql, String... fields) {
        ConnectionPoolManager poolManager = null;
        DruidPooledConnection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            poolManager = ConnectionPoolManager.getInstance();
            conn = poolManager.getConnection();
            stmt = conn.prepareStatement(sql);
            rs = stmt.executeQuery();
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            while (rs.next()) {
                Map<String, Object> map = new HashMap<String, Object>();
                for (String field : fields) {
                    if ("facepicurl".equals(field) == false) {
                        map.put(field, rs.getString(field));
                    } else {
                        Blob blob = rs.getBlob(field);
                        if (blob != null) {
                            map.put(field, getBlobImageData(blob));
                        } else {
                            map.put(field, null);
                        }
                    }
                }
                list.add(map);
            }
            return list;
        } catch (Exception e) {
            logger.error("执行数据库操作出错, SQL语句:" + sql, e);
        } finally {
            closeConnection(conn, stmt, rs);
        }
        return null;
    }

    public int queryTableDataCount(String sql) {
        ConnectionPoolManager poolManager = null;
        DruidPooledConnection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        int count = 0;
        try {
            poolManager = ConnectionPoolManager.getInstance();
            conn = poolManager.getConnection();
            stmt = conn.prepareStatement(sql);
            rs = stmt.executeQuery();
            while (rs.next()) {
                count = rs.getInt("totalNum");
            }
            return count;
        } catch (Exception e) {
            logger.error("执行数据库操作出错, SQL语句:" + sql, e);
        } finally {
            closeConnection(conn, stmt, rs);
        }
        return count;
    }

    /**
     * Blob字段转字节数组
     * @author fgq 2017年8月8日 下午2:03:07
     * @param blob
     * @return
     */
    private byte[] getBlobImageData(Blob blob) {
        BufferedInputStream is = null;
        byte[] bt = null;

        try {
            is = new BufferedInputStream(blob.getBinaryStream());
            int bufferSize = (int)blob.length();
            bt = new byte[bufferSize];
            try {
                is.read(bt, 0, bufferSize);
            } catch (Exception e) {
                logger.error("从数据库读取图片文件数据出错", e);
            }
        } catch (Exception e) {
            logger.error("从数据库读取图片文件数据出错", e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                }
            }
        }
        return bt;
    }
    public static boolean validConnection(String validSql) {
        ConnectionPoolManager poolManager = null;
        DruidPooledConnection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            poolManager = ConnectionPoolManager.getInstance();
            conn = poolManager.getConnection();
            stmt = conn.prepareStatement(validSql);
            rs = stmt.executeQuery();
            while (rs.next()) {
                int ret = rs.getInt(1);
                if (ret == 1) {
                    return true;
                }
            }
        } catch (Exception e) {
            logger.error("执行数据库操作出错, SQL语句:" + validSql, e);
        } finally {
            closeConnection(conn, stmt, rs);
        }
        return false;
    }

    public static void executeInsertSQL(String[] textData, String sql) {
        ConnectionPoolManager poolManager = null;
        DruidPooledConnection conn = null;
        PreparedStatement prep = null;
        try {
            poolManager = ConnectionPoolManager.getInstance();
            conn = poolManager.getConnection();
            prep = conn.prepareStatement(sql);
            prep.setString(1, textData[0].replace("\"", ""));
            prep.setString(2, textData[1].replace("\"", ""));
            prep.setString(3, textData[10].replace("\"", ""));
            prep.setString(4, textData[5].replace("\"", ""));
            prep.setString(5, textData[7].replace("\"", ""));
            prep.executeUpdate();
        } catch (Exception e) {
            logger.error("执行数据库操作出错, SQL语句:" + sql, e);
        } finally {
            closeConnection(conn, prep, null);
        }
    }

    public static int executeInsertSQL(List<File> listFile, String sql) {
        ConnectionPoolManager poolManager = null;
        DruidPooledConnection conn = null;
        PreparedStatement prep = null;
        int ret = 0;
        try {
            poolManager = ConnectionPoolManager.getInstance();
            conn = poolManager.getConnection();
            prep = conn.prepareStatement(sql);
            for(File file : listFile){
                prep.setString(1, UUIDUtil.getRandomUUID());
                String fileName = file.getName();
                String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
                fileName = fileName.substring(0, fileName.lastIndexOf("."));
                prep.setString(2, fileName);
                byte[] imageUrl = FileUtils.File2byte(file);
                ByteArrayInputStream inputstr = new ByteArrayInputStream(imageUrl);
                prep.setBinaryStream(3, inputstr, imageUrl.length);
                prep.setString(4, suffix);
                prep.addBatch();
            }
            int[] result = prep.executeBatch();
            ret = result.length;
        } catch (Exception e) {
            logger.error("执行数据库操作出错, SQL语句:" + sql, e);
        } finally {
            closeConnection(conn, prep, null);
        }
        return ret;
    }

    /**
     * 关闭连接资源
     * @author fgq 2017年8月8日 下午2:02:13
     * @param connection
     * @param stmt
     * @param rs
     */
    private static void closeConnection(DruidPooledConnection connection,Statement stmt, ResultSet rs){
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                logger.error("ResultSet关闭失败",e);
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (Exception e) {
                logger.error("Statement关闭失败",e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                logger.error("DruidPooledConnection关闭失败",e);
            }
        }
    }
}
